/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Frame.java
 *
 * Created on 9 mars 2010, 15:15:44
 */

package testmultinxt;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import lejos.nxt.Battery;
import lejos.nxt.Motor;
import lejos.nxt.Sound;
import lejos.nxt.remote.NXTCommand;
import lejos.nxt.remote.RemoteBattery;
import lejos.nxt.remote.RemoteMotor;
import lejos.pc.comm.NXTComm;
import lejos.pc.comm.NXTCommException;
import lejos.pc.comm.NXTCommFactory;
import lejos.pc.comm.NXTInfo;

/**
 *
 * @author Alan
 */
public class Frame2 extends javax.swing.JFrame {

    private NXTInfo[] nxts = null;
    private NXTComm[] nxtComms = null;


    /** Creates new form Frame */
    public Frame2() throws NXTCommException {
        initComponents();

        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                for (int i = 0; i < nxts.length; i++) {
                    if (nxtComms[i] != null) {
                        try {
                            nxtComms[i].close();
                            //nxtCommands[i].close();
                            System.out.println("Connexion à " + nxtList.getItem(i) + " fermée.");
                        } catch (IOException ex) {
                            ex.printStackTrace();
                        }
                    }
                }
            }
        });
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        searchButton = new javax.swing.JButton();
        nxtList = new java.awt.List();
        batteryButton = new javax.swing.JButton();
        startMButton = new javax.swing.JButton();
        stopMButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        textField = new javax.swing.JTextArea();
        bipButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        searchButton.setText("Search NXTs");
        searchButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                searchButtonActionPerformed(evt);
            }
        });

        nxtList.setMultipleMode(true);

        batteryButton.setText("Récupérer les niveaux de batterie");
        batteryButton.setEnabled(false);
        batteryButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                batteryButtonActionPerformed(evt);
            }
        });

        startMButton.setText("Démarrer moteurs");
        startMButton.setEnabled(false);
        startMButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                startMButtonActionPerformed(evt);
            }
        });

        stopMButton.setText("Arrêter moteurs");
        stopMButton.setEnabled(false);
        stopMButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                stopMButtonActionPerformed(evt);
            }
        });

        textField.setColumns(20);
        textField.setRows(5);
        jScrollPane1.setViewportView(textField);

        bipButton.setText("Bip");
        bipButton.setEnabled(false);
        bipButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bipButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(searchButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(nxtList, javax.swing.GroupLayout.DEFAULT_SIZE, 102, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(startMButton, javax.swing.GroupLayout.DEFAULT_SIZE, 168, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(stopMButton, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(batteryButton, javax.swing.GroupLayout.DEFAULT_SIZE, 280, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(bipButton))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 333, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(searchButton)
                    .addComponent(batteryButton)
                    .addComponent(bipButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 213, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(startMButton)
                            .addComponent(stopMButton)))
                    .addComponent(nxtList, javax.swing.GroupLayout.DEFAULT_SIZE, 247, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchButtonActionPerformed
        try {
            this.nxtList.removeAll();
            this.nxtList.add("...");
            this.batteryButton.setEnabled(false);
            this.textField.setEnabled(false);
            this.startMButton.setEnabled(false);
            this.stopMButton.setEnabled(false);
            this.bipButton.setEnabled(true);


            // demande de faire une recherche des NXTs allumés aux alentour
            nxts = NXTCommFactory.createNXTComm(NXTCommFactory.BLUETOOTH)
                        .search(null, NXTCommFactory.BLUETOOTH);

            // fin recherche
            this.nxtList.removeAll();
            
            if (nxts.length < 1) {
                // aucun NXT trouvé
                this.nxtList.add("Aucun NXT trouvé.");

            } else {
                // initialise le tableau des NXTComm
                this.nxtComms = new NXTComm[nxts.length];

                // met à jour la liste
                for (int i = 0; i < nxts.length; i++) {
                    this.nxtList.add(nxts[i].name);
                }

                // enable des boutons
                this.batteryButton.setEnabled(true);
                this.textField.setEnabled(true);
                this.startMButton.setEnabled(true);
                this.stopMButton.setEnabled(true);
            }
            
        } catch (NXTCommException ex) {
            ex.printStackTrace();
        }

    }//GEN-LAST:event_searchButtonActionPerformed

    private void batteryButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_batteryButtonActionPerformed
        final int[] selectedNXTs = this.nxtList.getSelectedIndexes();

        for ( int i = 0; i < selectedNXTs.length; i++) {
            try {
                // création de la connexion si nécessaire
                if (this.nxtComms[selectedNXTs[i]] == null) {
                    this.nxtComms[selectedNXTs[i]] = NXTCommFactory.createNXTComm(NXTCommFactory.BLUETOOTH);
                    this.textField.setText(this.textField.getText() + "\n" +
                                    "Connexion à " + this.nxtList.getItem(selectedNXTs[i]));
                    if (! this.nxtComms[selectedNXTs[i]].open(nxts[selectedNXTs[i]])) {
                        this.textField.setText(this.textField.getText() + "\n" +
                                    "Echec connexion à " + this.nxtList.getItem(selectedNXTs[i]) + ".");
                    } else {
                        this.textField.setText(this.textField.getText() + "\n" + "Connexion ok.");
                    }
                }

                // envoi de la commande
                final int index = i;
                MyNXTCommand.send(this.nxtComms[selectedNXTs[i]], new MyNXTCommand.Callback() {

                    public void call() {
                        textField.setText(textField.getText() + "\n" +
                                nxtList.getItem(selectedNXTs[index]) + " : " + Battery.getVoltage() + " V");
                    }
                });
                
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }//GEN-LAST:event_batteryButtonActionPerformed

    private void startMButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_startMButtonActionPerformed
        final int[] selectedNXTs = this.nxtList.getSelectedIndexes();

        for (int i = 0; i < selectedNXTs.length; i++) {
            try {
                // création de la connexion si nécessaire
                if (this.nxtComms[selectedNXTs[i]] == null) {
                    this.nxtComms[selectedNXTs[i]] = NXTCommFactory.createNXTComm(NXTCommFactory.BLUETOOTH);
                    this.textField.setText(this.textField.getText() + "\n" +
                                    "Connexion à " + this.nxtList.getItem(selectedNXTs[i]));
                    if (! this.nxtComms[selectedNXTs[i]].open(nxts[selectedNXTs[i]])) {
                        this.textField.setText(this.textField.getText() + "\n" +
                                    "Echec connexion à " + this.nxtList.getItem(selectedNXTs[i]) + ".");
                    } else {
                        this.textField.setText(this.textField.getText() + "\n" + "Connexion ok.");
                    }

                }

                // envoi de la commande
                final int index = i;
                MyNXTCommand.send(this.nxtComms[selectedNXTs[i]], new MyNXTCommand.Callback() {

                    public void call() {
                        Motor.A.forward();
                        Motor.B.forward();
                        textField.setText(textField.getText() + "\n" +
                                nxtList.getItem(selectedNXTs[index]) + " : moteurs lancés.");
                    }
                });

            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }//GEN-LAST:event_startMButtonActionPerformed

    private void stopMButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_stopMButtonActionPerformed
        final int[] selectedNXTs = this.nxtList.getSelectedIndexes();

        for (int i = 0; i < selectedNXTs.length; i++) {
            try {
                // création de la connexion si nécessaire
                if (this.nxtComms[selectedNXTs[i]] == null) {
                    this.nxtComms[selectedNXTs[i]] = NXTCommFactory.createNXTComm(NXTCommFactory.BLUETOOTH);
                    this.textField.setText(this.textField.getText() + "\n" +
                                    "Connexion à " + this.nxtList.getItem(selectedNXTs[i]));
                    if (! this.nxtComms[selectedNXTs[i]].open(nxts[selectedNXTs[i]])) {
                        this.textField.setText(this.textField.getText() + "\n" +
                                    "Echec connexion à " + this.nxtList.getItem(selectedNXTs[i]) + ".");
                    } else {
                        this.textField.setText(this.textField.getText() + "\n" + "Connexion ok.");
                    }
                }

                // envoi de la commande
                final int index = i;
                MyNXTCommand.send(this.nxtComms[selectedNXTs[i]], new MyNXTCommand.Callback() {

                    public void call() {
                        Motor.A.stop();
                        Motor.B.stop();
                        textField.setText(textField.getText() + "\n" +
                                nxtList.getItem(selectedNXTs[index]) + " : moteurs arrêtés.");
                    }
                });
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }//GEN-LAST:event_stopMButtonActionPerformed

    private void bipButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bipButtonActionPerformed
        final int[] selectedNXTs = this.nxtList.getSelectedIndexes();

        for ( int i = 0; i < selectedNXTs.length; i++) {
            try {
                // création de la connexion si nécessaire
                if (this.nxtComms[selectedNXTs[i]] == null) {
                    this.nxtComms[selectedNXTs[i]] = NXTCommFactory.createNXTComm(NXTCommFactory.BLUETOOTH);
                    this.textField.setText(this.textField.getText() + "\n" +
                                    "Connexion à " + this.nxtList.getItem(selectedNXTs[i]));
                    if (! this.nxtComms[selectedNXTs[i]].open(nxts[selectedNXTs[i]])) {
                        this.textField.setText(this.textField.getText() + "\n" +
                                    "Echec connexion à " + this.nxtList.getItem(selectedNXTs[i]) + ".");
                    } else {
                        this.textField.setText(this.textField.getText() + "\n" + "Connexion ok.");
                    }

                }

                // envoi de la commande
                final int index = i;
                MyNXTCommand.send(this.nxtComms[selectedNXTs[i]], new MyNXTCommand.Callback() {

                    public void call() {
                        Sound.playTone(500, 2000);
                        textField.setText(textField.getText() + "\n" +
                                nxtList.getItem(selectedNXTs[index]) + " est en train de biper !");
                    }
                });

            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }//GEN-LAST:event_bipButtonActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton batteryButton;
    private javax.swing.JButton bipButton;
    private javax.swing.JScrollPane jScrollPane1;
    private java.awt.List nxtList;
    private javax.swing.JButton searchButton;
    private javax.swing.JButton startMButton;
    private javax.swing.JButton stopMButton;
    private javax.swing.JTextArea textField;
    // End of variables declaration//GEN-END:variables

}
